package com.shigu.passageway.processes;

import com.opentae.data.mall.beans.*;
import com.opentae.data.mall.examples.MoPassagewayAccountExample;
import com.opentae.data.mall.examples.MoSettlementExample;
import com.opentae.data.mall.examples.MoWxuserinfoExample;
import com.opentae.data.mall.interfaces.*;
import com.shigu.agent.exceptions.AgentException;
import com.shigu.agent.processes.AgentProcess;
import com.shigu.main4.common.util.MoneyUtil;
import com.shigu.main4.common.util.SecretUtil;
import com.shigu.passageway.Passageway;
import com.shigu.passageway.bo.RegistBO;
import com.shigu.passageway.exceptions.PassagewayException;
import com.shigu.passageway.exceptions.YeepayException;
import com.shigu.wx.web.WxTempleateBaseData;
import com.shigu.wx.web.services.WxTokenService;
import com.yeepay.skb.biz.*;
import com.yeepay.skb.results.*;
import com.yeepay.skb.util.AESUtil;
import com.yeepay.skb.util.Conts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("yeepayPassageway")
public class YeepayPassageway implements Passageway{

    private static final Logger logger = LoggerFactory.getLogger(YeepayPassageway.class);

    private final Long passagewayId=1L;//本通道的通道ID

    private Double defaultRate;//默认费率

    private Double cashMoney;//默认结算费

    @Autowired
    private MoPassagewayAccountMapper moPassagewayAccountMapper;

    @Autowired
    private MoPassagewayMapper moPassagewayMapper;

    @Autowired
    private ManagerUserMapper managerUserMapper;

    @Autowired
    private MoCardMapper moCardMapper;

    @Autowired
    private MoOrderMapper moOrderMapper;

    @Autowired
    private MoSettlementMapper moSettlementMapper;

    @Autowired
    private AgentProcess agentProcess;

    @Autowired
    private MoShareProfitMapper moShareProfitMapper;

    @Autowired
    private MoWxuserinfoMapper moWxuserinfoMapper;

    @Autowired
    private WxTokenService wxTokenService;

    @Value("${main_host}")
    private String MAIN_HOST;

    private Double systemRate;

    @Value("${me.flag}")
    private String OEM_FLAG;

    @Value("${wx.template.payed}")
    private String PAYED_NOTIFY;

    @Value("${wx.notify.admin}")
    private String ADMIN_NOTIFY;

    private String callBackUrl;//收款成功回调，服务器对服务器的
    private String webCallBackUrl;//网页的回调
    private String msgCallBackUrl;//短信已发回调

    private String settlementCallBackUrl;//分润结算回调

    @PostConstruct
    public void init(){
        callBackUrl=MAIN_HOST+"bus/payedCallBack.htm";
        webCallBackUrl=MAIN_HOST+"backtest.html";
        msgCallBackUrl=MAIN_HOST+"bus/msgedCallback.htm";
        settlementCallBackUrl=MAIN_HOST+"bus/settlementCallback.htm";
        MoPassageway passageway=moPassagewayMapper.selectByPrimaryKey(passagewayId);
        defaultRate=Double.valueOf(passageway.getSysMax());
        cashMoney=Double.valueOf(passageway.getCashMoney());
        systemRate=Double.valueOf(passageway.getSysMin());
    }

    @Override
    public String regist(RegistBO bo) throws PassagewayException {
        //检查有没有开过户
        MoPassagewayAccountExample example=new MoPassagewayAccountExample();
        example.createCriteria().andBodyNumberEqualTo(bo.getIdCard());
        List<MoPassagewayAccount> yeepays=moPassagewayAccountMapper.selectByExample(example);
        if (yeepays.size()>0) {//已经开过户了
            new YeepayException("0006","一个身份证只能开一个账号").throwMe();
        }
        ManagerUser user=managerUserMapper.selectByPrimaryKey(bo.getUserId());
        RegisterPartsBuilder builder=new RegisterPartsBuilder();
        builder.setMainCustomerNumber(Conts.customerNumber);
        builder.setRequestId(bo.getUserId()+"_mh2_"+OEM_FLAG);
        builder.setCustomerType("PERSON");
        builder.setBindMobile(user.getLoginName());
        builder.setSignedName(bo.getRealName());
        builder.setLinkMan("郑涵韬");
        builder.setIdCard(bo.getIdCard());
        builder.setLegalPerson("郑涵韬");
        builder.setMinSettleAmount("1");
        builder.setRiskReserveDay("0");
        builder.setBankAccountNumber(bo.getBankAccountNumber());
        builder.setBankName(bo.getBankName());
        builder.setAccountName(bo.getRealName());
        builder.setAreaCode(bo.getAreaCode());
        //如果是商户要上传身份证和银行卡照片，如果是代理，使用默认照片
        String filePath=this.getClass().getResource("/")+"person.jpg";
        if (filePath.startsWith("file:")) {
            filePath=filePath.replace("file:","");
        }
        File f=new File(filePath);
        try {
            builder.setBankCardPhoto(f);
            builder.setIdCardPhoto(f);
            builder.setIdCardBackPhoto(f);
            builder.setPersonPhoto(f);
        } catch (Exception e) {
            logger.error("图片找不到");
        }
        builder.setWhiteList("1");
        RegisterPartsResult registerPartsResult= null;
        try {
            registerPartsResult = builder.exec(RegisterPartsResult.class);
        } catch (IOException e) {
            throw new YeepayException(e.getMessage());
        }
        if (!"0000".equals(registerPartsResult.getCode())) {
            throw new YeepayException(registerPartsResult.getCode(),registerPartsResult.getMessage());
        }

        //默认给他审核通过
        AuditMerchantPartsBuilder merchantBuilder=new AuditMerchantPartsBuilder();
        merchantBuilder.setMainCustomerNumber(Conts.customerNumber);
        merchantBuilder.setCustomerNumber(registerPartsResult.getCustomerNumber());
        merchantBuilder.setStatus("SUCCESS");
        try {
            AuditMerchantPartsResult auditResult=merchantBuilder.exec(AuditMerchantPartsResult.class);
            if(!auditResult.imSuccess()){
                logger.error("子商户审核"+auditResult.getCode()+"  "+auditResult.getMessage());
            }
        } catch (IOException e) {
            throw new YeepayException(e.getMessage());
        }
        MoPassagewayAccount passagewayAccount=new MoPassagewayAccount();
        passagewayAccount.setBankLocation(bo.getBankLocation());
        passagewayAccount.setBankName(bo.getBankName());
        passagewayAccount.setBankNumber(bo.getBankAccountNumber());
        passagewayAccount.setBankUser(bo.getRealName());
        passagewayAccount.setBodyNumber(bo.getIdCard());
        passagewayAccount.setRealName(passagewayAccount.getBankUser());
        passagewayAccount.setAccountCode(registerPartsResult.getCustomerNumber());
        passagewayAccount.setUserId(user.getUserId());
        passagewayAccount.setRate(defaultRate.toString());
        passagewayAccount.setPassagewayId(passagewayId);
        passagewayAccount.setAreaCode(bo.getAreaCode());
        passagewayAccount.setTelephone(bo.getTelephone());
        passagewayAccount.setLastModifyTime(new Date());
        passagewayAccount.setCashMoney(bo.getCashMoney()==null?cashMoney.toString():bo.getCashMoney());
        moPassagewayAccountMapper.insertSelective(passagewayAccount);
        ManagerUser upuser=new ManagerUser();
        upuser.setRealName(bo.getRealName());
        upuser.setIdCard(bo.getIdCard());
        upuser.setBankName(bo.getBankName());
        upuser.setBankNumber(bo.getBankAccountNumber());
        upuser.setUserId(bo.getUserId());
        upuser.setHasRealName(true);
        managerUserMapper.updateByPrimaryKeySelective(upuser);
        //设置默认分润
        try {
            defaultRate(passagewayAccount.getAccountCode(),defaultRate);
        } catch (IOException e) {
            throw new YeepayException("因为没设置成功费率导致的失败");
        }
        return passagewayAccount.getAccountCode();
    }

    @Override
    public String updateInfo(RegistBO bo) throws PassagewayException {
        MoPassagewayAccountExample example=new MoPassagewayAccountExample();
        example.createCriteria().andBodyNumberEqualTo(bo.getIdCard()).andPassagewayIdEqualTo(1L);
        List<MoPassagewayAccount> yeepays=moPassagewayAccountMapper.selectByExample(example);
        MoPassagewayAccount moYeepay;
        if (yeepays.size()==0) {
            throw new YeepayException("此身份证在本系统没有创建过账户【yp】");
        }
        moYeepay=yeepays.get(0);
        CustomerInforUpdatePartsBuilder builder=new CustomerInforUpdatePartsBuilder();
        builder.setMainCustomerNumber(Conts.customerNumber);
        builder.setCustomerNumber(moYeepay.getAccountCode());
        builder.setModifyType("2");//修改银行卡信息
        builder.setBankCardNumber(bo.getBankAccountNumber());
        builder.setBankName(bo.getBankName());
        builder.setRiskReserveDay("0");
        try {
            CustomerInforUpdatePartsResult result=builder.exec(CustomerInforUpdatePartsResult.class);
            if (!result.imSuccess()) {
                throw new YeepayException(result.getCode(),result.getMessage());
            }
            MoPassagewayAccount yp=new MoPassagewayAccount();
            yp.setBankName(bo.getBankName());
            yp.setBankNumber(bo.getBankAccountNumber());
            yp.setBankLocation(bo.getBankLocation());
            yp.setAccountId(moYeepay.getAccountId());
            yp.setBankUser(bo.getRealName());
            yp.setRealName(bo.getRealName());
            yp.setTelephone(bo.getTelephone());
            yp.setLastModifyTime(new Date());
            yp.setCashMoney(bo.getCashMoney()==null?cashMoney.toString():bo.getCashMoney());
            moPassagewayAccountMapper.updateByPrimaryKeySelective(yp);
            //更新managerUser
            ManagerUser user=new ManagerUser();
            user.setRealName(bo.getRealName());
            user.setIdCard(bo.getIdCard());
            user.setBankName(bo.getBankName());
            user.setBankNumber(bo.getBankAccountNumber());
            user.setUserId(bo.getUserId());
            managerUserMapper.updateByPrimaryKeySelective(user);
            return yp.getAccountCode();
        } catch (IOException e) {
            throw new YeepayException(e.getMessage());
        }
    }

    @Override
    public String toPay(Long userId,Long creditCardId,Double withdrawalMoney) throws PassagewayException {
        //查出开户信息和信用卡
        if (withdrawalMoney%1000==0) {
            new YeepayException("银联风控，1000或1000的位数禁止刷").throwMe();
        }
//        withdrawalMoney=1d;
        ManagerUser user=managerUserMapper.selectByPrimaryKey(userId);
        MoCard card=moCardMapper.selectByPrimaryKey(creditCardId);
        MoPassagewayAccountExample accountExample=new MoPassagewayAccountExample();
        accountExample.createCriteria().andUserIdEqualTo(userId).andPassagewayIdEqualTo(1L);
        MoPassagewayAccount yeepay=moPassagewayAccountMapper.selectByExample(accountExample).get(0);
        if (user == null||card == null||yeepay == null|| !card.getUserId().equals(userId)
                ||!yeepay.getUserId().equals(user.getUserId())) {
            throw new YeepayException("参数异常");
        }
        MoOrder order=new MoOrder();
        order.setCashNo(yeepay.getBankNumber());
        order.setCreditNo(card.getBankNo());
        order.setMcc("5311");
        order.setMobileName(user.getLoginName());
        order.setMoney(withdrawalMoney.toString());
        order.setSource("B");
        order.setUserId(userId);
        order.setCreditBank(card.getBankName());
        order.setCreditIcon(card.getBankIcon());
        order.setPassagewayId(yeepay.getPassagewayId());
        order.setRate(yeepay.getRate());
        moOrderMapper.insertSelective(order);

        ReceviePartsBuiler builer=new ReceviePartsBuiler();
        builer.setMainCustomerNumber(Conts.customerNumber);;
        builer.setAmount(withdrawalMoney.toString());
        builer.setWebCallBackUrl(webCallBackUrl);
        builer.setCallBackUrl(callBackUrl);
        builer.setCustomerNumber(yeepay.getAccountCode());
        builer.setMcc("5311");
        builer.setMobileNumber(user.getLoginName());
        builer.setSource("B");
        builer.setDescription("");
        builer.setPayerBankAccountNo(card.getBankNo());
        builer.setAutoWithdraw("false");
        builer.setWithdrawCardNo("");
        builer.setCustomTradeFee("");
        builer.setProductVersion("");
//        builer.setWithdrawCallBackUrl(webCallBackUrl);
        builer.setSmgCallBackUrl(msgCallBackUrl);
        String orderCode=OEM_FLAG+"order_"+order.getOrderId();
        builer.setRequestId(orderCode);
        MoOrder o=new MoOrder();
        o.setOrderId(order.getOrderId());
        o.setOrderCode(orderCode);
        moOrderMapper.updateByPrimaryKeySelective(o);
        try {
            ReceviePartsResult result=builer.exec(ReceviePartsResult.class);
            if (result.imSuccess()) {
                return AESUtil.decrypt(result.getUrl(), Conts.hmacKey);
            }else{
                throw new YeepayException(result.getCode(),result.getMessage());
            }
        } catch (IOException e) {
            throw new YeepayException(e.getMessage());
        }
    }

    @Override
    public void payCallBack(Long orderId,Double amount,Double fee,String paystatus) throws PassagewayException {
        MoOrder order=moOrderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            new YeepayException(orderId+" 订单不存在").throwMe();
        }
        MoSettlementExample example=new MoSettlementExample();
        example.createCriteria().andOrderIdEqualTo(orderId);
        if (moSettlementMapper.countByExample(example)>0) {
            throw new YeepayException(orderId+" 已经结算过了");
        }
        //1、结算走一波
        //计算结算金额
        String settlementFee= MoneyUtil.formatMoney(amount-fee);
        //更新订单状态
        int status;
        switch (paystatus){
            case "INIT":status=2; break;
            case "SUCCESS":status=3; break;
            case "FAIL":status=4; break;
            case "FROZEN":status=5; break;
            case "THAWED":status=6; break;
            case "REVERSE":status=7; break;
            default:status=1;
        }
        MoOrder od=new MoOrder();
        od.setOrderId(orderId);
        od.setStatus(status);
        od.setFee(MoneyUtil.formatMoney(fee));
        moOrderMapper.updateByPrimaryKeySelective(od);

        order.setStatus(status);
        order.setFee(od.getFee());
        if (!"SUCCESS".equals(paystatus)) {
            throw new YeepayException(orderId+" 结算状态为"+paystatus);
        }
        //结算记录走一波
        MoSettlement settlement=new MoSettlement();
        settlement.setOrderId(orderId);
        settlement.setSettlementTime(new Date());
        settlement.setMoney(settlementFee);
        //得到开户行信息
        BusinessBankAccount bankAccount=managerUserMapper.selBusinessAccount(order.getUserId(),passagewayId);
        settlement.setBankName(bankAccount.getBankName());
        settlement.setBankNumber(bankAccount.getBankNumber());
        settlement.setStatus(1);
        moSettlementMapper.insertSelective(settlement);
        WithdrawBuilder builder=new WithdrawBuilder();
        builder.setAmount(settlementFee);
        builder.setCustomerNumber(bankAccount.getAccountCode());
        builder.setExternalNo(OEM_FLAG+"settlement_"+settlement.getSettlementId());
        builder.setMainCustomerNumber(Conts.customerNumber);
        builder.setTransferWay("1");
        builder.setCallBackUrl(settlementCallBackUrl);
        WithdrawResult result= null;
        try {
            result = builder.exec(WithdrawResult.class);
            if (!result.imSuccess()) {
                throw new YeepayException(orderId+" "+result.getMessage());
            }
        } catch (IOException e) {
            logger.error("网络原因请求失败",e);
        }
        toMakeProfit(settlement.getSettlementId(),order);//分润先分掉
    }

    @Override
    public void setFee(Long agentId,Long businessId,Double rate,Double settleMoney) throws PassagewayException {
        BusAndAgentRate barate=managerUserMapper.selBusAndAgentRate(businessId,passagewayId);
        rate=rate/100;
        //1、检验是代理和商户是否匹配
        if (!barate.getAgentId().equals(agentId)) {
            new YeepayException("商户ID数据非法").throwMe();
        }
        superSetFee(businessId,rate,barate.getAgentRate(),settleMoney);
    }

    @Override
    public void superSetFee(Long userId, Double rate,Double limitRate,Double settleMoney) throws PassagewayException {
        //2、检测新费率是否合法
        if(rate<limitRate){
            new YeepayException("商户费率不能小于代理费率").throwMe();
        }
        //3、执行修改
        MoPassagewayAccountExample accountExample=new MoPassagewayAccountExample();
        accountExample.createCriteria().andUserIdEqualTo(userId).andPassagewayIdEqualTo(1L);
        accountExample.setStartIndex(0);
        accountExample.setEndIndex(1);
        MoPassagewayAccount updateAccount=new MoPassagewayAccount();
        updateAccount.setRate(rate.toString());
        if (settleMoney != null) {
            updateAccount.setCashMoney(MoneyUtil.formatMoney(settleMoney));
        }
        moPassagewayAccountMapper.updateByExampleSelective(updateAccount,accountExample);
        MoPassagewayAccount yeepay=moPassagewayAccountMapper.selectByConditionList(accountExample).get(0);

        try {
            FeeSetPartsBuilder builder=new FeeSetPartsBuilder();
            builder.setGroupCustomerNumber(Conts.customerNumber);
            builder.setCustomerNumber(yeepay.getAccountCode());
            builder.setProductType("1");
            builder.setRate(MoneyUtil.dealRate4(rate));
            FeeSetResult result=builder.exec(FeeSetResult.class);
            if (!result.imSuccess()) {
                logger.error(userId+"1这个用户默认费率没设置不成功"+result.getMessage());
                throw new YeepayException(result.getMessage());
            }
            if (settleMoney != null) {
                builder=new FeeSetPartsBuilder();
                builder.setGroupCustomerNumber(Conts.customerNumber);
                builder.setCustomerNumber(yeepay.getAccountCode());
                builder.setProductType("3");
                builder.setRate(settleMoney.longValue()+"");
                result=builder.exec(FeeSetResult.class);
                if (!result.imSuccess()) {
                    logger.error(userId+"2这个用户默认费率没设置不成功"+result.getMessage());
                    throw new YeepayException(result.getMessage());
                }
            }
            builder=new FeeSetPartsBuilder();
            builder.setGroupCustomerNumber(Conts.customerNumber);
            builder.setCustomerNumber(yeepay.getAccountCode());
            builder.setProductType("4");
            builder.setRate("0");
            result=builder.exec(FeeSetResult.class);
            if (!result.imSuccess()) {
                logger.error(userId+"4这个用户默认费率没设置不成功"+result.getMessage());
                throw new YeepayException(result.getMessage());
            }
            builder=new FeeSetPartsBuilder();
            builder.setGroupCustomerNumber(Conts.customerNumber);
            builder.setCustomerNumber(yeepay.getAccountCode());
            builder.setProductType("5");
            builder.setRate("0");
            result=builder.exec(FeeSetResult.class);
            if (!result.imSuccess()) {
                logger.error(userId + "5这个用户默认费率没设置不成功"+result.getMessage());
                throw new YeepayException(result.getMessage());
            }
        } catch (IOException e) {
            throw new YeepayException("接口通讯异常");
        }
    }

    @Override
    public Double getSystemRate() {
        return 0.0038d;
    }

    /**
     * 默认分润
     * @param yeePayCode 易宝唯一码
     * @param rate 费率
     */
    @Transactional(rollbackFor = Exception.class)
    public void defaultRate(String yeePayCode,Double rate) throws IOException {
        FeeSetPartsBuilder builder=new FeeSetPartsBuilder();
        builder.setGroupCustomerNumber(Conts.customerNumber);
        builder.setCustomerNumber(yeePayCode);
        builder.setProductType("1");
        builder.setRate(rate.toString());
        FeeSetResult result=builder.exec(FeeSetResult.class);
        if (!result.imSuccess()) {
            logger.error(yeePayCode+"1这个用户默认费率没设置不成功");
        }
        builder=new FeeSetPartsBuilder();
        builder.setGroupCustomerNumber(Conts.customerNumber);
        builder.setCustomerNumber(yeePayCode);
        builder.setProductType("3");
        builder.setRate(cashMoney.longValue()+"");
        result=builder.exec(FeeSetResult.class);
        if (!result.imSuccess()) {
            logger.error(yeePayCode+"2这个用户默认费率没设置不成功");
        }
        builder=new FeeSetPartsBuilder();
        builder.setGroupCustomerNumber(Conts.customerNumber);
        builder.setCustomerNumber(yeePayCode);
        builder.setProductType("4");
        builder.setRate("0");
        result=builder.exec(FeeSetResult.class);
        if (!result.imSuccess()) {
            logger.error(yeePayCode+"4这个用户默认费率没设置不成功");
        }
        builder=new FeeSetPartsBuilder();
        builder.setGroupCustomerNumber(Conts.customerNumber);
        builder.setCustomerNumber(yeePayCode);
        builder.setProductType("5");
        builder.setRate("0");
        result=builder.exec(FeeSetResult.class);
        if (!result.imSuccess()) {
            logger.error(yeePayCode+"5这个用户默认费率没设置不成功");
        }
    }

    /**
     * 给代理分润
     * @param settlementId
     * @throws YeepayException
     */
    public void toMakeProfit(Long settlementId,MoOrder order) throws YeepayException {

        //代理费率
        SettleRate settAgentRate=managerUserMapper.selAgentRateBySettleId(settlementId,passagewayId);
        if (settAgentRate == null) {
            throw new YeepayException(order.getOrderId()+"_取代理分润信息失败");
        }
        Double agentRate=settAgentRate.getRate();
        if (agentRate == null||agentRate<systemRate) {
            agentRate=systemRate;
        }
        //实际手续费-代理的成本手续费=代理的利润
        Double profitMoney=Double.valueOf(order.getFee())-Double.valueOf(settAgentRate.getTradeMoney())*agentRate;
        if (profitMoney>0) {//如果等于0就没什么好分的啦
            //加余额
            try {
                agentProcess.increaseProfile(settAgentRate.getUserId(),profitMoney);
            } catch (AgentException e) {
                throw new YeepayException(e.getMessage());
            }
        }else{
            profitMoney=0d;
        }
        MoShareProfit profit=new MoShareProfit();
        profit.setAgentId(settAgentRate.getUserId());
        profit.setBusinessId(order.getUserId());
        profit.setCreateTime(new Date());
        profit.setOrderId(settAgentRate.getOrderId());
        profit.setTradeMoney(settAgentRate.getTradeMoney());
        profit.setProfitMoney(profitMoney.toString());
        profit.setCostRate(order.getRate());
        moShareProfitMapper.insertSelective(profit);

        if (profitMoney<=0) {
            return;
        }

        ManagerUser user=managerUserMapper.selectByPrimaryKey(order.getUserId());

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //发送分润提醒，先查出代理openid如果 没有则不发
        MoWxuserinfoExample wxExample=new MoWxuserinfoExample();
        wxExample.createCriteria().andUserIdEqualTo(settAgentRate.getUserId());
        wxExample.setStartIndex(0);
        wxExample.setEndIndex(1);
        List<MoWxuserinfo> wxinfos=moWxuserinfoMapper.selectByConditionList(wxExample);
        Map<String,WxTempleateBaseData> wxTempleateDataMap=new HashMap<>();
        wxTempleateDataMap.put("first",new WxTempleateBaseData("恭喜你，获得一笔分润佣金！"));
        wxTempleateDataMap.put("keyword1",new WxTempleateBaseData(MoneyUtil.formatMoney(profitMoney)));
        wxTempleateDataMap.put("keyword2",new WxTempleateBaseData(sdf.format(new Date())));
        wxTempleateDataMap.put("remark",new WxTempleateBaseData(SecretUtil.secretName(user.getRealName()) +
                "消费了"+MoneyUtil.formatMoney(order.getMoney())+"元"));
        String targetopenid="";
        if (wxinfos.size()>0) {
            MoWxuserinfo wxuser=wxinfos.get(0);
            try {
                String token=wxTokenService.getSystemToken().getAccess_token();
                wxTokenService.sendTemplateMsg(PAYED_NOTIFY,wxuser.getOpenId(),wxTempleateDataMap,MAIN_HOST+"wappage/agpage/tradeDetail",token);
                targetopenid=wxuser.getOpenId();
            } catch (Exception e) {
                logger.error("获取token失败",e);
            }
        }
        //发给老赵一份
        if (!ADMIN_NOTIFY.equals(targetopenid)) {
            wxTempleateDataMap.put("first",new WxTempleateBaseData("恭喜["+settAgentRate.getUserId()+"]，获得一笔分润佣金！","#9E272A"));
            try {
                String token=wxTokenService.getSystemToken().getAccess_token();
                wxTokenService.sendTemplateMsg(PAYED_NOTIFY,ADMIN_NOTIFY,wxTempleateDataMap,MAIN_HOST+"wappage/agpage/tradeDetail",token);
            } catch (Exception e) {
                logger.error("发消息失败",e);
            }
        }
    }

}
